<?php
session_start();

require_once "jssdk.php";
$jssdk = new JSSDK("wxea46661fa20c8760", "922dac02fb4f4b5d753c09d4673ae2e6");
$signPackage = $jssdk->GetSignPackage();
var_dump($signPackage);
function httpGet($url) {
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_TIMEOUT, 500);
    // 为保证第三方服务器与微信服务器之间数据传输的安全性，所有微信接口采用https方式调用，必须使用下面2行代码打开ssl安全校验。
    // 如果在部署过程中代码在此处验证失败，请到 http://curl.haxx.se/ca/cacert.pem 下载新的证书判别文件。
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
    //验证token, 本地可以注释掉, 上线必须打开
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, true);
    curl_setopt($curl, CURLOPT_URL, $url);
    $res = curl_exec($curl);
    curl_close($curl);
    return $res;
}
//1.用户在微信点击确认登录后,会跳转到此页面,同时传入一个参数code
$code = $_GET["code"];
//2.通过code来请求access_token 和openid
$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wxea46661fa20c8760&secret=922dac02fb4f4b5d753c09d4673ae2e6&code={$code}&grant_type=authorization_code";
$result = httpGet($url);
$arr = json_decode($result,true);
$token = $arr["access_token"];
$openid = $arr["openid"];
if (strlen($openid) > 0){
    $_SESSION["openid"] = $openid;
}else{
    $openid = $_SESSION["openid"];
}
//3.通过access_token和openid获取用户详细信息
$url = "https://api.weixin.qq.com/sns/userinfo?access_token={$token}&openid={$openid}&lang=zh_CN";
$result = httpGet($url);
$arr = json_decode($result,true);

//连接数据库
mysql_connect(	SAE_MYSQL_HOST_M.":".SAE_MYSQL_PORT,SAE_MYSQL_USER,	SAE_MYSQL_PASS);
mysql_select_db(SAE_MYSQL_DB);
mysql_query("set names utf8");

$sql = "SELECT * FROM chong WHERE openid='{$openid}'";
$result = mysql_query($sql);
if(mysql_num_rows($result)>0){
    // 存在

}else{


    $sql = "INSERT INTO chong (id,openid,score,jiangpin,name,tel,address) VALUES (NULL,'{$openid}','','','','','')";
    mysql_query($sql);
    if(mysql_insert_id()>0){

    }else{

    }
}
echo "<script>var openid = '{$openid}'; </script>";

?>



<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
    <title>Title</title>
    <style>


    </style>
    <link rel="stylesheet" href="css/page1&2.css">
    <link rel="stylesheet" href="css/page13.css">
    <script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
</head>
<body>
<!-----------------------第一页------------->
    <div id="one">
        <img src="img/tiaozhan.png" alt="###" id="tiaozhan">
        <img src="img/guize.png" alt="###" id="guize">
        <img src="img/bg2.png" alt="###" id="bg2">
        <img src="img/logo.png" alt="###" id="logo">
        <img src="img/sanshimiao.png" alt="###" id="sanshimiao">
        <img src="img/niyexiangzuo.png" alt="###" id="niyexiangzuo">
        <img src="img/dizhonghai.png" alt="###" id="dizhonghai">
    </div>

<!----------------------第二页-------------->
    <div id="two">
        <img src="img/kaishibutton.png" alt="###" id="kaishi">
        <img src="img/logo.png" alt="###" id="logo1">
    </div>

<!-------------------第三页游戏开始------->
<div id="three">
    <img src="img/honglvdeng1.png" alt="###" id="hldeng">
    <img src="img/jishi.png" alt="###" id="jishi">
    <img src="img/xian.png" alt="###" id="xian">
    <!--<div id="gameOver">你撞啦</div>-->
    <h3 id="ready">READY</h3>
    <div id="numdaojishi">30秒</div>
    <canvas id="canvas" width="500" height="500"></canvas>
</div>

<div id="four">
    <!--<img src="img/bg5b.png" alt="###" id="bg5b">-->
    <div id="wenzi">
        <p>
            你只闯过了
        <p id="shuliang"></p>
         个障碍胜出全国
        <p id="baifenbi">100%</p>
        的玩家
        </p>
    </div>
    <a href="index.php"><img src="img/again.png" alt="" id="again"></a>
</div>

<div id="five">
   <div id="wenzi2">
       <p>
           你共闯过了
       <p id="shuliang2"></p>
       个障碍物胜出全国
       <p id="baifenbi2">100%</p>
       玩家
       </p>
   </div>
    <img src="img/yaoqing.png" alt="" id="yaoqing">
    <img src="img/paihangbang.png" alt="" id="paihangbang">
</div>

<div id="six"></div>
<div id="seven">
    <ul id="mingci">
        <span>名次</span>
        <span>微信昵称</span>
        <span>闯过障碍数</span>
        <li>
            <span>1</span>
            <span>2</span>
            <span>3</span>
        </li>


    </ul>

</div>

    <script src="js/jquery-2.1.3.min.js" type="text/javascript" charset="utf-8"></script>
    <script src="js/touch.min.js" type="text/javascript" charset="utf-8"></script>
    <script src="js/loading.js" type="text/javascript" charset="utf-8"></script>

    <script>
 /***第一页JS********/
        touch.on("#guize","touchstart",function (){
            $("#bg2").show();
        });
        touch.on("#bg2","touchstart",function (){
            $("#bg2").hide();
        });

        $('#logo').fadeOut(500);        //淡出
        $('#logo').fadeIn(500);         //淡入

        $("#tiaozhan").animate({
            opacity:1
        },1000);
        $("#guize").animate({
            opacity:1
        },2000);
/********第一页转第二页JS********/
        touch.on("#tiaozhan","touchstart",function () {
            $("#one").hide();
            $("#two").show();
        });

        setInterval(function () {
            $('#logo1').fadeOut(300);        //淡出
            $('#logo1').fadeIn(300);         //淡入
        },5000);

/**************点击邀请倒是分享到朋友圈******************/
touch.on("#yaoqing","touchstart",function () {
    $("#five").hide();
    $("#six").show();
    touch.on("#six","touchstart",function () {
        $("#five").show();
        $("#six").hide();
    })
});
 touch.on("#seven","touchstart",function () {
     $("#seven").hide();
     $("#five").show();
 });
touch.on("#paihangbang","touchstart",function () {
    $("#seven").show();
    $("#five").hide();
})



 /*****************第三页游戏开始*******/
        touch.on("#kaishi","touchstart",function () {
            $("#two").hide();
            $("#three").show();

            loading({
                youxibg:"img/youxibg.png",
                dichel:"img/dichel.png",
                dicher:"img/dicher.png",
                zhangai:"img/zhangai.png",
                speed:"img/speed.png",
                jiansu:"img/jiansu.png",
                xian:"img/xian.png",
                xiaoxuanfeng:"img/xiaoxuanfeng.png",
                leftbutton:"img/leftbutton.png",
                rightbutton:"img/rightbutton.png",
                jishi:"img/jishi.png",
                honglvdeng1:"img/honglvdeng1.png",
                honglvdeng2:"img/honglvdeng2.png",
                honglvdeng3:"img/honglvdeng3.png",
                xian:"img/xian.png",
                jiasuche:"img/jiasuche.png"


            },{
                complete:main
            })

            /**********************红绿灯更换***********************/
            var t = 1;
            var timer = setInterval(function () {
                t++;
                if (t == 1){
                    $("#hldeng").attr("src",'img/honglvdeng1.png');
                }
                if (t == 2){
                    $("#hldeng").attr("src",'img/honglvdeng2.png');
                }
                if (t == 3){
                    $("#hldeng").attr("src",'img/honglvdeng3.png');
                }
                if (t ==4){
                    /***********************红路灯,字ready,起跑线逐渐消失****************************/
                    $("#hldeng").animate({
                        opacity:0,
                        top:0
                    },1000);
                    $("#ready").animate({
                        opacity:0,
                        top:50
                    },2000);
                    $("#xian").animate({
                        top:668
                    },2500);

                    clearInterval(timer);

                }
            },1000);
            setTimeout(function () {
                $("#xian").hide()
            },6000);



        })
        var start = true;
        var canvas = document.getElementById("canvas");
        var ctx = canvas.getContext("2d");
// 屏幕宽高
 var SCREEN_WIDTH = document.documentElement.clientWidth;
 var SCREEN_HEIGHT = document.documentElement.clientHeight;

 canvas.width = SCREEN_WIDTH;
 canvas.height = SCREEN_HEIGHT;

// loading({
//     youxibg:"img/youxibg.png",
//     dichel:"img/dichel.png",
//     dicher:"img/dicher.png",
//     zhangai:"img/zhangai.png",
//     speed:"img/speed.png",
//     jiansu:"img/jiansu.png",
//     xian:"img/xian.png",
//     xiaoxuanfeng:"img/xiaoxuanfeng.png",
//     leftbutton:"img/leftbutton.png",
//     rightbutton:"img/rightbutton.png",
//     jishi:"img/jishi.png",
//     honglvdeng1:"img/honglvdeng1.png",
//     honglvdeng2:"img/honglvdeng2.png",
//     honglvdeng3:"img/honglvdeng3.png",
//     xian:"img/xian.png"
//
//
// },{
//     complete:main
// })
 function rand(min,max) {
     return Math.floor(Math.random()*(max - min + 1)+min);
 }

//碰撞检测的函数判断
 function checkP(obj1,obj2){
     if(Math.abs(obj1.x + obj1.w / 2 - (obj2.x + obj2.w / 2)) <= obj1.w / 2 + obj2.w / 2 && Math.abs(obj1.y + obj1.h / 2 - (obj2.y + obj2.h / 2)) <= obj1.h / 2 + obj2.h / 2) {
         return true;

     } else {
         return false;
     }
 }
// 记分数
 function Score(obj1,obj2) {
     if ((obj2.y)>(obj1.y+obj1.h)){
         return true;
     }else{
         return false;
     }

 }
 var fen = 0;

function main(obj) {
//    自己的车
    carImg = obj.xiaoxuanfeng;
    var car = {
        img:carImg,
        w:canvas.width/10,
        h:canvas.height/8,
        x:SCREEN_WIDTH/2-carImg.width/2+50,
        y:SCREEN_HEIGHT-carImg.height - 20
    };

//火箭
    speedImg = obj.speed;
    var speed = {
        img:speedImg,
        w:60,
        h:80,
        x:310,
        y:550

    };
//    左右按钮
    leftbuttonImg =obj.leftbutton;
    var leftbutton = {
        img:leftbuttonImg,
        w:canvas.width/8,
        h:canvas.height/10,
        x:100,
        y:550
    };
    rightbuttonImg =obj.rightbutton;
    var rightbutton = {
        img:rightbuttonImg,
        w:canvas.width/8,
        h:canvas.height/10,
        x:250,
        y:550
    };

//    红绿灯
    honglvdengImg = obj.honglvdeng1;
    var deng = {
        img:honglvdengImg,
        w:50,
        h:100,
        x:180,
        y:300
    }

    var type = 1;
    var scrollY = 0;
    var sudu = 1;
    var s =5;
    var enemys=[];

    function drawBack() {
        ctx.clearRect(0,0,SCREEN_WIDTH,SCREEN_HEIGHT)
        scrollY++;
        sudu+=s;
        if (scrollY>=SCREEN_HEIGHT){
            scrollY = 0
        }
        if (sudu>=SCREEN_HEIGHT){
            sudu = 0
        }


        //    画背景

        ctx.drawImage(obj.youxibg,0,sudu,SCREEN_WIDTH,SCREEN_HEIGHT);
        ctx.drawImage(obj.youxibg,0,sudu - SCREEN_HEIGHT,SCREEN_WIDTH,SCREEN_HEIGHT)
//       画其他
        ctx.drawImage(speed.img,speed.x,speed.y,speed.w,speed.h)
//    画小车
        ctx.drawImage(car.img,car.x,car.y,car.w,car.h);

        window.requestAnimationFrame(drawBack);
//        左右按钮
        ctx.drawImage(leftbutton.img,leftbutton.x,leftbutton.y,leftbutton.w,leftbutton.h);
        ctx.drawImage(rightbutton.img,rightbutton.x,rightbutton.y,rightbutton.w,rightbutton.h);


//        敌车
        function Enemy() {
            this.img = obj.zhangai;
            this.w = canvas.width/15;
            this.h = canvas.height/20;
            this.x = rand(0,SCREEN_WIDTH - this.w);
            this.y = -this.h;
            this.speed = 1;
            this.type = 2;

            this.length = 5;

            this.playIndex = 1;
        }

        Enemy.prototype.draw = function () {
            ctx.drawImage(this.img,this.x,this.y,this.w,this.h);
        };
        Enemy.prototype.move = function () {
            this.y += s;
        };

//        判断是否清除
        Enemy.prototype.canClear = function () {
            if (this.y>=car.y+car.h){
                return true;
            }else{
                return false;
            }
        };
        Enemy.prototype.changeType = function(type) {
            this.type = type;
            switch(this.type) {
                case 1:
                    break;
                case 2:
                    this.img = obj.dicher;
                    this.w = canvas.width/9;
                    this.h = canvas.height/8;
                    this.x = rand(0, SCREEN_WIDTH - this.w);
                    this.y = -this.h;
                    this.speed = 1;
                    break;
                case 3:
                    this.img = obj.dichel;
                    this.w = canvas.width/9;
                    this.h = canvas.height/8;
                    this.x = rand(0, SCREEN_WIDTH - this.w);
                    this.y = -this.h;
                    this.speed = 1;
                    break;
                default:
                    break;
            }
        };

  //创建敌车
        if (scrollY%33 ==0){
            var enemy = new Enemy(obj.zhangai);
            if (scrollY%55 == 0){
                enemy.changeType(2);
            }else if (scrollY%77 ==0){
                enemy.changeType(3);
            }
            enemys.push(enemy);
        }
//        画敌车
        for(var i = 0;i< enemys.length;i++){
            var enemy = enemys[i];
            if (enemy.canClear()){
                enemys.splice(i,1);
                i--;
            }
            enemy.draw();
            enemy.move();
        }
//判断碰撞检测
        for(var j = 0; j < enemys.length; j++) {
            if(checkP(car, enemys[j])) {
                four.style.display = "block";
                three.style.display = "none";
                shuliang.innerHTML = fen;
                start = false;
                sudu = 0;
                s = 0;
            }

        }
//       积分
        for(var k = 0;k<enemys.length;k++){
            if(Score(car, enemys[k])) {
                fen+=1;
//                start = false;
            }
        }
    }
/************************左右点击事件**************************************/
    canvas.addEventListener("touchstart",function () {
        var x = event.touches[0].clientX;
        var y = event.touches[0].clientY;
//            console.log(x,y)
/************************点击后,加速,减速*************************************/
        if (x >= speed.x && x <= speed.x+speed.w &&y>=speed.y && y<=speed.y+speed.h){
            type++;
            if(type == 1){
                speed.img = obj.speed;
                car.img = obj.xiaoxuanfeng;
                s=5;
            }else if (type == 2){
                speed.img = obj.jiansu;
                car.img = obj.jiasuche;
                type = 0;
                s = 10;
            }

        }

/*********************左右按钮*************************/

        if (x >= leftbutton.x && x <= leftbutton.x+leftbutton.w &&y>=leftbutton.y && y<=leftbutton.y+leftbutton.h){
            car.x -=10
        }
        if (x >= rightbutton.x && x <= rightbutton.x+rightbutton.w &&y>=rightbutton.y && y<=rightbutton.y+rightbutton.h){
            car.x +=10
        }
        if (car.x+car.w>canvas.width){
            car.x = canvas.width - car.w
        }
        if (car.x < 0 ){
            car.x = 0
        }
    },false);



//    画一遍静止的游戏界面
    ctx.drawImage(obj.youxibg,0,0,SCREEN_WIDTH,SCREEN_HEIGHT);
    ctx.drawImage(speed.img,speed.x,speed.y,speed.w,speed.h)
//    画小车
    ctx.drawImage(car.img,car.x,car.y,car.w,car.h);
//        左右按钮
    ctx.drawImage(leftbutton.img,leftbutton.x,leftbutton.y,leftbutton.w,leftbutton.h);
    ctx.drawImage(rightbutton.img,rightbutton.x,rightbutton.y,rightbutton.w,rightbutton.h);

   var timer = setTimeout(function () {
       drawBack();

       var tt =5;
       var time1 = setInterval(function () {
           if (start == false){
               clearInterval(time1)
           }
           --tt;
           numdaojishi.innerHTML = tt + "秒";
           if (tt == 0){
               clearInterval(time1);
               five.style.display = "block";
               three.style.display = "none";
               shuliang2.innerHTML = fen;

               $.ajax({
                    url:"choujiang_api.php",
                   type:"get",
                   dataType:"json",
                   data:{
                        type:"score",
                       openid:openid,
                       score:$("#shuliang2").val()
                   },
                   success:function (data) {
                       console.log(data)
                   }

               })

               sudu = 0;
               s = 0
           }

       },1000);
   },3000)


}



 /***************************点击再来一次后刷新页面*********************************/
// $("#again").on("touchstart",function () {
//     $("#three").show();
//     $("#four").hide();
//     alert("点到了") ;
////            window.requestAnimationFrame(drawBack);
// })



        document.body.addEventListener("touchstart", function() {
            document.body.addEventListener("touchmove", function() {
                event.preventDefault();
            }, false);
        }, false);


 wx.config({
     debug: true,
     appId: '<?php echo $signPackage["appId"];?>',
     timestamp: <?php echo $signPackage["timestamp"];?>,
     nonceStr: '<?php echo $signPackage["nonceStr"];?>',
     signature: '<?php echo $signPackage["signature"];?>',
     jsApiList: [
         // 所有要调用的 API 都要加到这个列表中
         "onMenuShareTimeline"
     ]
 });
 wx.ready(function () {
     // 在这里调用 API
     wx.onMenuShareTimeline({
         title: '快来帮好友抽奖', // 分享标题
         link: 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxea46661fa20c8760&redirect_uri=http://pkqpkq.applinzi.com/chongchongchong/choujiang.php&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect', // 分享链接
         imgUrl: 'http://pic.58pic.com/58pic/12/46/16/28A58PIC4m6.jpg', // 分享图标
         success: function () {
             // 用户确认分享后执行的回调函数
             alert("分享成功！");
         },
         cancel: function () {
             // 用户取消分享后执行的回调函数
             alert("取消分享");
         }
     });





    </script>

</body>
</html>